﻿
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;

using Rvt2ifcTool.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Rvt2ifcTool
{
	internal class RestUtils
	{
		public static ILog log { get { return LogManager.GetLogger(typeof(RestUtils)); } }
		private static string getBaseUrl()
		{
			return "http://10.3.35.13:8086/rvt2ifc-service";
		}
		private static string getToken()
		{
			// 判断 Token 是否超过 2 小时
			if (string.IsNullOrEmpty(_token) || DateTime.UtcNow - _tokenAcquiredTime > TimeSpan.FromHours(1))
			{
				_token = getTokenByService();
				_tokenAcquiredTime = DateTime.UtcNow;
			}
			return _token;
		}
		private static DateTime _tokenAcquiredTime;
		private static string _token = string.Empty;
		private static string getTokenByService()
		{
			try
			{
				var client = new RestClient(getBaseUrl() + "/user/login");
				client.Timeout = -1;
				var request = new RestRequest(Method.POST);
				request.AddHeader("Content-Type", "application/json");
				var body = @"{" + "\n" +
				@"    ""username"": ""xuegang""," + "\n" +
				@"    ""password"": ""sippr@073111""" + "\n" +
				@"}";
				request.AddParameter("application/json", body, ParameterType.RequestBody);
				IRestResponse response = client.Execute(request);
				var apiResponse = JsonConvert.DeserializeObject<ApiResponse<string>>(response.Content);
				// 访问解析后的数据
				if (apiResponse?.data != null)
				{
					string token = apiResponse.data;

					return token;
				}
				else
				{
					return null;
				}
			}
			catch (Exception ex)
			{

				log.Error(ex);
				return null;
			}

		}
		public static List<UploadedFile> GetWaitList()
		{
			try
			{
				var client = new RestClient(getBaseUrl() + "/file/getWaitList");
				client.Timeout = 500000;
				var request = new RestRequest(Method.GET);
				request.AddHeader("Authorization", "Bearer " + getToken());
				IRestResponse response = client.Execute(request);
				var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<UploadedFile>>>(response.Content);
				// 访问解析后的数据
				if (apiResponse?.code == 0 && apiResponse?.data != null)
				{
					List<UploadedFile> list = apiResponse.data;
					return list;
				}
				return null;
			}
			catch (Exception ex)
			{
				log.Error(ex);
				return null;
			}

		}
		public static List<Project> GetWaitCombinList()
		{
			try
			{
				var client = new RestClient(getBaseUrl() + "/project/getWaitList");
				client.Timeout = 500000;
				var request = new RestRequest(Method.GET);
				request.AddHeader("Authorization", "Bearer " + getToken());
				IRestResponse response = client.Execute(request);
				var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<Project>>>(response.Content);
				// 访问解析后的数据
				if (apiResponse?.code == 0 && apiResponse?.data != null)
				{
					List<Project> list = apiResponse.data;
					return list;
				}
				return null;
			}
			catch (Exception)
			{

				return null;
			}

		}
		public static bool UpdateXktState(string fileUuid, int state)
		{
			try
			{
				var client = new RestClient(getBaseUrl() + "/xkt/updateState?fileUuid=" + fileUuid + "&state=" + state);
				client.Timeout = 500000;
				var request = new RestRequest(Method.POST);
				request.AddHeader("Authorization", getToken());
				IRestResponse response = client.Execute(request);
				var apiResponse = JsonConvert.DeserializeObject<ApiResponse<object>>(response.Content);
				// 访问解析后的数据
				if (apiResponse?.code == 0 && apiResponse?.data != null)
				{
					if (apiResponse.code == 0)
						return true;
				}
				return false;
			}
			catch (Exception)
			{

				return false;
			}

		}
		public static bool UpdateProjectState(string projectUuid, int state)
		{
			try
			{
				var client = new RestClient(getBaseUrl() + "/project/updateState?projectUuid=" + projectUuid + "&state=" + state);
				client.Timeout = 500000;
				var request = new RestRequest(Method.POST);
				request.AddHeader("Authorization", getToken());
				IRestResponse response = client.Execute(request);
				var apiResponse = JsonConvert.DeserializeObject<ApiResponse<object>>(response.Content);
				// 访问解析后的数据
				if (apiResponse?.code == 0 && apiResponse?.data != null)
				{
					if (apiResponse.code == 0)
						return true;
				}
				return false;
			}
			catch (Exception)
			{

				return false;
			}

		}
		public static async Task<string> DownLoadFile(string dir, string storedName)
		{
			string baseUrl = getBaseUrl() + "/file/download/" + storedName;
			string savePath = Path.Combine(dir, storedName);

			using (HttpClient client = new HttpClient())
			{
				client.DefaultRequestHeaders.Add("Authorization", getToken());

				try
				{
					using (HttpResponseMessage response = await client.GetAsync(baseUrl, HttpCompletionOption.ResponseHeadersRead))
					{
						if (!response.IsSuccessStatusCode)
						{
							log.Error($"下载失败: {response.StatusCode}");
							return null;
						}

						using (var stream = await response.Content.ReadAsStreamAsync())
						using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
						{
							await stream.CopyToAsync(fileStream);
						}
						return savePath;
					}
				}
				catch (Exception ex)
				{
					log.Error(ex);
				}
			}
			return null;
		}
		//public static string DownLoadFile(string dir, string storedName)
		//{
		//	// 服务端下载接口的 URL
		//	string baseUrl = getBaseUrl() + "/file/download/" + storedName;
		//	string savePath = Path.Combine(dir, storedName); // 本地保存路径

		//	// 创建 RestClient 和 RestRequest
		//	var client = new RestClient(baseUrl);
		//	client.Timeout = 500000;
		//	var request = new RestRequest(Method.GET);
		//	request.AddHeader("Authorization", getToken());
		//	try
		//	{
		//		// 执行请求
		//		var response = client.DownloadData(request);

		//		if (response != null)
		//		{
		//			// 将文件保存到本地
		//			File.WriteAllBytes(savePath, response);
		//		}
		//		return savePath;
		//	}
		//	catch (Exception ex)
		//	{
		//		log.Error(ex);
		//	}
		//	return null;
		//}

	}
}
